import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

enum _ChannelType {
  methodChannel,
  basicMessageChannel,
  eventChannel,
}

class ChannelDemoPage extends StatefulWidget {
  const ChannelDemoPage({Key? key}) : super(key: key);

  @override
  _ChannelDemoPageState createState() => _ChannelDemoPageState();
}

class _ChannelDemoPageState extends State<ChannelDemoPage>
    with TickerProviderStateMixin {
  _ChannelType _currentChannel = _ChannelType.methodChannel;

  late TabController _tabController;

  @override
  void initState() {
    super.initState();

    _tabController = TabController(
      length: 3,
      vsync: this, // this须实现mixin类 TickerProviderStateMixin
    );

    _tabController.addListener(() {
      // print('_tabController change: ${_tabController.index}'); // 会执行两次
      if (_tabController.animation?.value == _tabController.index) {
        print('_tabController change: ${_tabController.index}');
      }
    });

    _initBasicMethodCall();

    _testEventChannel();
  }

  String _methodChannelResultData = '';
  static MethodChannel methodChannel =
      const MethodChannel("com.tikeyc.fluttermodule/methodChannel");

  _testMethodCall() async {
    //2.通过invokeMethod调用Native方法，拿到返回值
    String debugString = await methodChannel.invokeMethod(
        "testMethodCall", "give me debug info");
    setState(() {
      _methodChannelResultData = debugString;
    });
    print('test debugString=$debugString');
  }

  String basicMethodChannel = "com.tikeyc.fluttermodule/basicMethodChannel";
  late final BasicMessageChannel _basicMessageChannel;
  String _basicMessageChannelResultData = '';

  _initBasicMethodCall() {
    //1.创建Flutter端的BasicMessageChannel
    _basicMessageChannel =
        BasicMessageChannel(basicMethodChannel, const StringCodec());
    //2.接收来自Native的消息，并向Native回复
    _basicMessageChannel.setMessageHandler((message) {
      print('test 原生端发来的消息：$message');
      showDialog(
        barrierDismissible: false, // 点击遮罩层是否隐藏，默认true
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('提示信息'),
            content: Text('test 原生端发来的消息：$message'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  print('确定');
                },
                child: const Text('确定'),
              ),
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  print('取消');
                },
                child: const Text('取消'),
              ),
            ],
          );
        },
      );
      return Future.value('flutter tikeyc');
    });
  }

  _testBasicMessageCall() async {
    String replyString =
        await _basicMessageChannel.send("Android, 我是Flutter端！");
    setState(() {
      _basicMessageChannelResultData = replyString;
    });
    print('test Android端回复的的消息：$replyString');
  }

  String eventChannelTag = 'com.tikeyc.fluttermodule/eventChannel';
  late StreamSubscription _streamSubscription;
  String _eventChannelResultData = '';

  _testEventChannel() {
    //1.创建Flutter端EventChannel
    EventChannel eventChannel = EventChannel(eventChannelTag);
    //2.EventChannel#receiveBroadcastStream注册listener，建立监听
    _streamSubscription = eventChannel.receiveBroadcastStream().listen(
      (event) {
        print("receiveBroadcastStream : ${event.toString()}");
        setState(() {
          _eventChannelResultData = event.toString();
        });
      },
      onError: (errorcode) {
        print('errorcode: $errorcode');
      },
    );
  }

  @override
  void dispose() {
    super.dispose();

    _streamSubscription.cancel();
  }

  List<Widget> get _tabBarViews {
    return [
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ElevatedButton(
            onPressed: () {
              _testMethodCall();
            },
            child: const Text('调用原生方法'),
          ),
          const SizedBox(height: 20),
          Text(_methodChannelResultData),
        ],
      ),
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ElevatedButton(
            onPressed: () {
              _testBasicMessageCall();
            },
            child: const Text('调用原生方法'),
          ),
          const SizedBox(height: 20),
          Text(_basicMessageChannelResultData),
        ],
      ),
      Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text('请尝试调整手机的音量:'),
              const SizedBox(height: 30),
              const Text('receiveBroadcastStream:'),
              const SizedBox(height: 30),
              Text(
                _eventChannelResultData,
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('channel'),
      ),
      body: Column(
        children: [
          TabBar(
            controller: _tabController,
            isScrollable: true,
            indicator: const BoxDecoration(
              color: Colors.green,
              borderRadius: BorderRadius.all(
                Radius.circular(8),
              ),
            ),
            labelColor: Colors.white,
            unselectedLabelColor: Colors.black,
            // indicatorSize: TabBarIndicatorSize.label,
            tabs: const [
              Tab(
                child: Text('methodChannel'),
              ),
              Tab(
                child: Text('basicMessageChannel'),
              ),
              Tab(
                child: Text('eventChannel'),
              ),
            ],
            onTap: (value) {
              print('TabBar onTap: $value');
              if (value == 0) {
                _currentChannel = _ChannelType.methodChannel;
              } else if (value == 1) {
                _currentChannel = _ChannelType.basicMessageChannel;
              } else if (value == 2) {
                _currentChannel = _ChannelType.eventChannel;
              }
            },
          ),
          Expanded(
            flex: 1,
            child: TabBarView(
              controller: _tabController,
              children: _tabBarViews,
            ),
          ),
        ],
      ),
    );
  }
}
